<template>
  <div>
    <div class="pageTitleWhole">
      <div style="overflow: hidden">
        <a style="margin-right: 20px; margin-bottom: 15px; float: left;"><router-link :to="backUrl"><a-icon type="left" />返回</router-link></a>
        <a-breadcrumb>
          <a-breadcrumb-item><router-link :to="'/financialCenter/' + page.url">应{{payInfo}}账单</router-link></a-breadcrumb-item>
          <a-breadcrumb-item>应{{payInfo}}明细</a-breadcrumb-item>
        </a-breadcrumb>
      </div>
    </div>
    <div class="pageContentWhole pageContentWhole_detale">
      <!-- 账单信息 -->
      <a-card>
        <div class="card-title hasContent">账单信息</div>
        <a-descriptions :column="3">
          <a-descriptions-item label="对账单编号">{{detail.billCode}}</a-descriptions-item>
          <a-descriptions-item :label="`${bankInfo}款单位`">
            <router-link :to="{path: `${linkSuffix}`}" target="_blank">{{page.isPayOrRecevie ? detail.receivableCustName : detail.payableCustName}}</router-link>
          </a-descriptions-item>
          <a-descriptions-item :label="`${payInfo}款单位`">{{page.isPayOrRecevie ? detail.payableCustName : detail.receivableCustName}}</a-descriptions-item>
          <a-descriptions-item :label="`应${payInfo}总金额`"><span class='t_money_fh'>{{amountType}} </span><span class='t_money'>{{detail.totalAmount}}</span></a-descriptions-item>
          <a-descriptions-item :label="`${billOpt}总金额`"><span class='t_money_fh'>{{amountType}} </span><span class='t_money'>{{detail.invoiceAmount}}</span></a-descriptions-item>
          <a-descriptions-item :label="`已${payInfo}总金额`"><span class='t_money_fh'>{{amountType}} </span><span class='t_money'>{{detail.alreadyAmount}}</span></a-descriptions-item>
          <a-descriptions-item :label="`未${payInfo}总金额`"><span class='t_money_fh'>{{amountType}} </span><span class='t_money'>{{detail.remainingAmount}}</span></a-descriptions-item>
          <a-descriptions-item label="对账日期">{{detail.createTime}}</a-descriptions-item>
          <a-descriptions-item :label="`${billOpt}日期`">{{detail.lastInvoiceDate||'--'}}</a-descriptions-item>
          <a-descriptions-item label="截止日期">
            {{detail.endDate}}
            <a @click="setEndTime">设置</a>
          </a-descriptions-item>
          <a-descriptions-item label="结束日期">{{detail.completeTime||'--'}}</a-descriptions-item>
          <a-descriptions-item label="对账人">{{detail.operatorName}}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <span v-if="detail.status===1" style="color: red">未结清</span>
            <span v-if="detail.status===2" style="color: green">已结清</span>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>
    </div>

    <!-- 发票 -->
    <div class="pageContentWhole pageContentWhole_detale">
      <a-card>
        <div class="card-title hasContent">发票
          <div style="float: right"><a-button type="primary" @click="addInvoice">+ 添加发票</a-button></div>
        </div>
        <div v-for="item in billList" :key="item.id" class="invoiceItem">
          <a-row>
            <a-col :span="22" :style="item.invoiceType===4 ? {'paddingTop': '16px'} : {}">
              <a-descriptions :column="4">
                <a-descriptions-item label="票号" v-if="item.invoiceType!==4">{{item.invoiceNo||'--'}}</a-descriptions-item>
                <a-descriptions-item label="票据类型">{{item.invoiceType===1?'增值税专用发票':(item.invoiceType===2?'增值税普通发票': (item.invoiceType===3?'其它票据':'不开票'))}}</a-descriptions-item>
                <a-descriptions-item label="开票项目" v-if="item.invoiceType!==4">{{item.project||'--'}}</a-descriptions-item>
                <a-descriptions-item label="开票日期" v-if="item.invoiceType!==4">{{item.invoiceDate}}</a-descriptions-item>

                <a-descriptions-item label="金额(价税合计)" v-if="item.invoiceType!==4"><span class='t_money_fh'> {{amountType}} </span> <span class='t_money'>{{item.amount}}</span></a-descriptions-item>
                <a-descriptions-item label="税点(%)" v-if="item.invoiceType!==4">{{item.taxRate}}</a-descriptions-item>
                <a-descriptions-item label="税额" v-if="item.invoiceType!==4"><span class='t_money_fh'> {{amountType}} </span> <span class='t_money'>{{item.taxAmount}}</span></a-descriptions-item>
                <a-descriptions-item label="录入人">{{item.operatorName}}</a-descriptions-item>
                <a-descriptions-item label="日期" v-if="item.invoiceType===4">{{item.invoiceDate}}</a-descriptions-item>
              </a-descriptions>
            </a-col>
            <a-col :span="2">
               <div class="operationItems">
                  <a @click="editInvoice(item)">编辑</a>
                  <a @click="deleteInvoice(item.id)">删除</a>
                </div>
            </a-col>
          </a-row>
        </div>
      </a-card>
    </div>

    <!-- 资金 -->
    <div class="pageContentWhole pageContentWhole_detale">
      <a-card>
        <div class="card-title hasContent">资金
          <div style="float: right"><a-button type="primary" @click="addCapital">+ {{payInfo}}款记录</a-button></div>
        </div>
        <div v-for="item in capitalList" :key="item.id" class="invoiceItem">
          <a-row>
            <a-col :span="22">
              <a-descriptions :column="4">
                <a-descriptions-item :label="`${payInfo}款金额`"><span class='t_money_fh'>{{amountType}} </span> <span class='t_money'>{{item.amount}}</span></a-descriptions-item>
                <a-descriptions-item :label="`${payInfo}款银行`">{{item.capitalBank}}</a-descriptions-item>
                <a-descriptions-item :label="`${bankInfo}款银行`">{{item.transactionBank}}</a-descriptions-item>
                <a-descriptions-item label="录入人">{{item.operatorName}}</a-descriptions-item>

                <a-descriptions-item :label="`${payInfo}款时间`">{{item.transactionDate}}</a-descriptions-item>
                <a-descriptions-item :label="`${payInfo}款账号`">{{item.capitalAccount}}</a-descriptions-item>
                <a-descriptions-item :label="`${bankInfo}款账号`">{{item.transactionAccount}}</a-descriptions-item>
                <a-descriptions-item label="备注">{{item.remark}}</a-descriptions-item>
              </a-descriptions>
            </a-col>
            <a-col :span="2">
               <div class="operationItems">
                  <a @click="editCapital(item)">编辑</a>
                  <a @click="deleteCapital(item.id)">删除</a>
                </div>
            </a-col>
          </a-row>
        </div>
      </a-card>
    </div>

    <!-- 截止时间modal -->
    <a-modal
      :visible="dateVisible"
      title="设置账期截止日期"
      :confirmLoading="confirmLoading"
      :destroyOnClose="true"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model
        ref="rulesForm"
        :model="form" :label-col="labelCol" :wrapper-col="wrapperCol"
        :rules="rules"
      >
        <a-form-model-item label="账期截止日期" prop="endDate">
          <a-date-picker @change="onChangeEndDate"><a-icon slot="suffixIcon" type="calendar" /></a-date-picker>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 发票modal -->
    <invoiceModal :visible="invoiceVisible" :data="invoiceObj" @setData="setInvoiceData"></invoiceModal>

    <!-- 资金modal -->
    <capitalModal :visible="capitalVisible" :data="capitalObj" @setData="setCapitalData"></capitalModal>
  </div>
</template>

<script>
import invoiceModal from './invoiceModal'
import capitalModal from './capitalModal'
import {queryBillInfo, queryBillInvoiceList, deleteBillInvoice, updateBillEndDate,
  queryBillReceivablePayableList, deleteBillReceivablePayable} from '@/api/financialCenter'

const fomrMessage = `必填项不能为空`

export default {
  props: ['id'],
  data () {
    return {
      // 页面区分信息
      page: {
        url: '',
        isPayOrRecevie: true // t付 f收
      },
      detail: {},
      billList: [],
      capitalList: [],
      // date modal
      confirmLoading: false,
      dateVisible: false,
      labelCol: {span: 8},
      wrapperCol: {span: 14},
      rules: {
        endDate: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}]
      },
      form: {
        endDate: null
      },
      // invoice modal
      invoiceVisible: false,
      invoiceObj: {},
      // capitalList
      capitalVisible: false,
      capitalObj: {},
      backUrl: ''
    }
  },
  components: {
    invoiceModal,
    capitalModal
  },
  computed: {
    amountType () {
      return this.detail.currencyType === 'CNY' ? '¥' : (this.detail.currencyType === 'USD' ? '$' : '?')
    },
    // 收付金额
    payInfo () {
      return this.page.isPayOrRecevie ? '付' : '收'
    },
    // 收付银行
    bankInfo () {
      return this.page.isPayOrRecevie ? '收' : '付'
    },
    // 收，开票
    billOpt () {
      return this.page.isPayOrRecevie ? '收票' : '开票'
    },
    linkSuffix () {
      const isPay = this.page.isPayOrRecevie
      const t = this.page.t
      const custType = isPay ? this.detail.receivableCustType : this.detail.payableCustType
      let url = ''
      if (t === 'JIA_HUA_ORDER' || t === 'JIA_HUA_CONTAINER') {
        if (custType && ~custType.indexOf('CUSTOMER')) {
          url = `/salesCenter/customManage/${this.detail.payableCustId}`
          if (isPay) {
            url = `/salesCenter/customManage/${this.detail.receivableCustId}`
          }
        } else {
          if (isPay) url = `/supplierCenter/payableSettlementObject/${this.detail.receivableCustId}`
          else url = `/supplierCenter/receivableSettlementObject/${this.detail.payableCustId}`
        }
      } else if (t === 'JIA_HUA_SHIP_VOYAGE' || t === 'JIA_CHUANG') {
        if (isPay) url = `/shipCenter/copeWithSettlementObject/${this.detail.receivableCustId}`
        else url = `/shipCenter/receivableSettlementObject/${this.detail.payableCustId}`
      } else if (t === 'JIA_TE') {
        if (custType && ~custType.indexOf('CUSTOMER')) {
          url = `/landCenter/customManage/${this.detail.payableCustId}`
          if (isPay) {
            url = `/landCenter/customManage/${this.detail.receivableCustId}`
          }
        } else {
          if (isPay) url = `/landCenter/payableSettlementObject/${this.detail.receivableCustId}`
          else url = `/landCenter/receivableSettlementObject/${this.detail.payableCustId}`
        }
      }
      return url
    }
  },
  methods: {
    initDetail () {
      queryBillInfo({id: this.id}).then(rsp => {
        this.detail = rsp.data
      })
    },
    initInvoices () {
      queryBillInvoiceList({billId: this.id}).then(rsp => {
        this.billList = rsp.data
      })
    },
    initReceivablePayableList () {
      queryBillReceivablePayableList({billId: this.id}).then(rsp => {
        this.capitalList = rsp.data
      })
    },
    // 截止时间modal
    setEndTime () {
      if (!this.$root._bc.setTime) {
        this.$message.error('您无此权限！')
        return
      }
      this.form.endDate = null
      this.dateVisible = true
    },
    onChangeEndDate (date, dataStr) {
      this.form.endDate = dataStr
    },
    handleOk () {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          updateBillEndDate({id: this.id, ...this.form}).then(rsp => {
            this.$message.success('设置成功')
            this.initDetail() // 查询最新账单数据
            this.dateVisible = false
            this.confirmLoading = false
          }).catch(() => { this.confirmLoading = false })
        }
      })
    },
    handleCancel () {
      this.dateVisible = false
    },
    // 发票modal
    addInvoice () {
      if (!this.$root._bc.createInvoice) {
        this.$message.error('您无此权限！')
        return
      }
      this.invoiceObj = {
        billId: this.id,
        currencyType: this.detail.currencyType,
        rate: this.detail.rate,
        isPayOrRecevie: this.page.isPayOrRecevie
      }
      this.invoiceVisible = true
    },
    editInvoice (data) {
      if (!this.$root._bc.editInvoice) {
        this.$message.error('您无此权限！')
        return
      }
      this.invoiceObj = Object.assign({}, data, {
        currencyType: this.detail.currencyType,
        rate: this.detail.rate,
        isPayOrRecevie: this.page.isPayOrRecevie
      })
      this.invoiceVisible = true
    },
    deleteInvoice (id) {
      if (!this.$root._bc.dropInvoice) {
        this.$message.error('您无此权限！')
        return
      }
      let _t = this
      this.$confirm({
        title: '删除后将无法恢复且有可能会影响账单状态，确认删除？',
        onOk () {
          deleteBillInvoice({id}).then(rsp => {
            _t.$message.success('发票删除成功')
            _t.initInvoices() // 查询最新发票数据
            _t.initDetail()
          })
        }
      })
    },
    setInvoiceData (data) {
      if (data) {
        this.initInvoices() // 查询最新发票数据
        this.initDetail()
      }
      this.invoiceVisible = false
    },
    // 资金modal
    addCapital () {
      if (!this.$root._bc.createRecord) {
        this.$message.error('您无此权限！')
        return
      }
      this.capitalObj = {
        billId: this.id,
        currencyType: this.detail.currencyType,
        rate: this.detail.rate,
        isPayOrRecevie: this.page.isPayOrRecevie
      }
      this.capitalVisible = true
    },
    editCapital (data) {
      if (!this.$root._bc.editRecord) {
        this.$message.error('您无此权限！')
        return
      }
      this.capitalObj = Object.assign({}, data, {
        currencyType: this.detail.currencyType,
        rate: this.detail.rate,
        isPayOrRecevie: this.page.isPayOrRecevie
      })
      this.capitalVisible = true
    },
    deleteCapital (id) {
      if (!this.$root._bc.dropRecord) {
        this.$message.error('您无此权限！')
        return
      }
      let _t = this
      this.$confirm({
        title: '删除后将无法恢复且有可能会影响账单状态，确认删除？',
        onOk () {
          deleteBillReceivablePayable({id}).then(rsp => {
            _t.$message.success('付款记录删除成功')
            _t.initDetail()
            _t.initReceivablePayableList()
          })
        }
      })
    },
    setCapitalData (data) {
      if (data) {
        this.initDetail()
        this.initReceivablePayableList()
      }
      this.capitalVisible = false
    }
  },
  created () {
    const url = this.$route.meta.selectKeyUrl
    this.page.isPayOrRecevie = !!~url.indexOf('pay')
    this.page.url = url

    const t = this.$route.query.t
    this.page.t = t
    if (t === 'JIA_HUA_ORDER') {
      if (this.page.isPayOrRecevie) {
        this.backUrl = '/financialCenter/payableBillOfHuaJzx?f=1'
      } else {
        this.backUrl = '/financialCenter/receivableBillOfHuaJzx?f=1'
      }
    } else if (t === 'JIA_HUA_CONTAINER') {
      if (this.page.isPayOrRecevie) {
        this.backUrl = '/financialCenter/payableBillOfHuaXg?f=1'
      } else {
        this.backUrl = '/financialCenter/receivableBillOfHuaXg?f=1'
      }
    } else if (t === 'JIA_HUA_SHIP_VOYAGE') {
      if (this.page.isPayOrRecevie) {
        this.backUrl = '/financialCenter/payableBillOfHuaCb?f=1'
      } else {
        this.backUrl = '/financialCenter/receivableBillOfHuaCb?f=1'
      }
    } else if (t === 'JIA_CHUANG') {
      if (this.page.isPayOrRecevie) {
        this.backUrl = '/financialCenter/payableBillOfChuang?f=1'
      } else {
        this.backUrl = '/financialCenter/receivableBillOfChuang?f=1'
      }
    } else if (t === 'JIA_TE') {
      if (this.page.isPayOrRecevie) {
        this.backUrl = '/financialCenter/payableBillOfTe?f=1'
      } else {
        this.backUrl = '/financialCenter/receivableBillOfTe?f=1'
      }
    }
  },
  mounted () {
    this.initDetail()
    this.initInvoices()
    this.initReceivablePayableList()
  }
}
</script>

<style lang="less" scoped>
  .ant-card {
    margin-bottom: 24px;
    border: none;
    .card-title {
      position: relative;
      padding-left: 16px;
      font-size: 18px;
      line-height: 1;
      color: #000;
      &:before {
        content: "";
        width: 5px;
        height: 18px;
        background: #1890ff;
        border-radius: 4px;
        position: absolute;
        left: 0;
        top: -1px;
      }
    }
    .hasContent {
      margin-bottom: 20px;
      overflow: hidden;
    }
    .ant-col-12{ padding-right: 50px;}
  }

  .invoiceItem {
    border: 1px solid #e2e2e2;
    padding: 15px 15px 0 15px;
    margin: 15px 0;

    .operationItems {
      padding: 20px 0 20px 20px;
      border-left: 1px solid #e2e2e2;
    }
  }
</style>
